import { defineStore } from "pinia";
import { computed, ref, reactive, watchEffect } from "vue";
import { currentUser, login as userLogin, weChatLogin, type UserInfo } from "@/api/user";

export const useAccountStore = defineStore("account", () => {
  /** 身份令牌 */
  const token = ref<string | undefined | null>(uni.getStorageSync("token"));

  const isShowNeedBtn = ref(false);

  // #ifdef MP-WEIXIN
  if(uni.getAccountInfoSync().miniProgram.envVersion == 'release'){
    isShowNeedBtn.value = true;
  }
  // #endif

  /** 用户信息 */
  const userInfo = ref<UserInfo>({});

  /** 分享来源 */
  const shareInfo = ref<any>({
    id: undefined,
    uid: undefined
  });

  watchEffect(() => {
    if (token.value) {
      // 本地储存Token
      uni.setStorage({ key: "token", data: token.value });
      // Token变更，重新获取登录用户信息
      currentUser().then((data) => {
        userInfo.value = data
        if(data.isShowNeedBtn) {
          isShowNeedBtn.value = true;
        }
      });
    } else {
      userInfo.value = {}
      uni.removeStorage({ key: "token" });
    }
  });

  /** 登录 */
  async function login(args: Record<string, any>) {
    const data = await userLogin(args);
    token.value = data;
  }

  /** 小程序登录 */
  function loginMP() {
    return new Promise<any>((resolve, reject) => {
      uni.login({
        success: ({ code }) => {
          // 调用登陆接口
          uni.getUserInfo({
            success: async({userInfo}) => {
              const data = await weChatLogin({code, userInfo});
              token.value = data.access_token;
              resolve(code);
            }
          })
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  }

  /** 退出登录 */
  function logout() {
    token.value = "";
  }

  return {
    token,
    isShowNeedBtn,
    userInfo,
    shareInfo,
    login,
    loginMP,
    logout,
    hasLogin: computed(() => !!token.value),
  };
});
